<!DOCTYPE html>
<title>Service Worker: postMessage across processes</title>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="resources/test-helpers.js"></script>
<script>
if (window.testRunner) {
  testRunner.setPopupBlockingEnabled(false);
}

function open_url_in_new_window(url) {
  var a = document.createElement('a');
  a.href = url;
  // rel=noreferrer causes chrome to open the link in a new renderer process.
  a.setAttribute('rel', 'noreferrer');
  a.target = '_blank';
  a.click();
}

async_test(function(t) {
    var scope = 'resources/simple.html';
    var registration;
    service_worker_unregister_and_register(
        t, 'resources/postmessage-cross-process-worker.js', scope)
      .then(function(r) {
          registration = r;
          return wait_for_state(t, r.installing, 'activated');
        })
      .then(function() {
          var worker = registration.active;
          open_url_in_new_window(
              'resources/postmessage-cross-process-helper.html');
          var messageChannel = new MessageChannel();
          messageChannel.port1.onmessage = t.step_func(onMessage);
          worker.postMessage({resultport: messageChannel.port2},
                             [messageChannel.port2]);
        })
      .catch(unreached_rejection(t));

    var expected = [
      'Acking value: 1',
      'Acking value: 2',
    ];

    function onMessage(e) {
      var result = e.data;
      assert_array_equals(result, expected,
          'Worker should ack values posted by new window in order.');
      t.done();
    }
  }, 'postMessage MessagePorts from client to SW in a different process');
</script>
